package org.example.volunteerend.controller;

import org.example.volunteerend.common.Result;
import org.example.volunteerend.dto.UserLoginRequest;
import org.example.volunteerend.dto.UserRegisterRequest;
import org.example.volunteerend.entity.User;
import org.example.volunteerend.service.UserService;
import org.example.volunteerend.utils.AliOssUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody UserRegisterRequest request) {
        User user = userService.register(request);
        return Result.success("注册成功", user);
    }

    @PostMapping("/login")
    public Result<Object> login(@RequestBody UserLoginRequest request) {
        return Result.success("登录成功", userService.login(request));
    }

    @GetMapping("/{userId}")
    public Result<User> getUserInfo(@PathVariable Integer userId) {
        return Result.success(userService.getUserInfo(userId));
    }

    @PutMapping("/{userId}")
    public Result<Void> updateUserInfo(@PathVariable Integer userId, @RequestBody User user) {
        userService.updateUserInfo(userId, user);
        return Result.success("用户信息更新成功", null);
    }
    
    @PostMapping("/{userId}/avatar")
    public Result<Map<String, String>> updateAvatar(@PathVariable Integer userId, @RequestParam("avatar") MultipartFile avatar) {
        try {
            // 检查用户是否存在
            User user = userService.getUserInfo(userId);
            
            // 生成唯一文件名
            String originalFilename = avatar.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = "avatars/" + userId + "/" + UUID.randomUUID().toString() + extension;
            
            // 上传到阿里云OSS
            String avatarUrl = AliOssUtil.uploadFile(filename, avatar.getInputStream());
            
            // 更新用户头像URL
            User updateUser = new User();
            updateUser.setUserId(userId);
            updateUser.setAvatarUrl(avatarUrl);
            userService.updateUserInfo(userId, updateUser);
            
            // 返回结果
            Map<String, String> data = new HashMap<>();
            data.put("avatar_url", avatarUrl);
            return Result.success("头像更新成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("头像更新失败：" + e.getMessage());
        }
    }
} 